#admin.py
from flask import Blueprint,render_template, request, redirect, session
from AdminApiRunner.app import db
from AdminApiRunner.core.Utils import ReturnUtil, PasswdUtil
from .models import Admin
from functools import wraps

admin = Blueprint('admin',__name__)

# 登录、注册认证函数
def authorize(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        admin = session.get('admin_login', None)
        if admin:
            return func(*args, **kwargs)
        else:
            return ReturnUtil.Error(status=-1, msg="未登录", data=None)

    return wrapper

@admin.route('/index')
def index():
    return render_template('admin/index.html')


@admin.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get("username", None)
        password = request.form.get("password", None)
        adminInfo = Admin.query.filter_by(username=username).first
        if adminInfo:
            if PasswdUtil.md5(password) == adminInfo.password:
                session['admin_login'] = adminInfo
                return ReturnUtil.Success(data=adminInfo)
            else:
                return ReturnUtil.Error(msg="密码错误")
        else:
            return ReturnUtil.Error(msg="用户不存在")

    else:
        adminInfo = session.get('admin_login', None)
        if adminInfo:
            return ReturnUtil.Success(data=adminInfo)
        else:
            return ReturnUtil.Error(status=-1, msg="未登录", data=None)


@admin.route('/list',methods=['GET','POST'])
@authorize
def list():
    admins = Admin.query.all()
    return ReturnUtil.Success(data=admins)

@admin.route('/add',methods=['POST','GET'])
@authorize
def add():
    if request.method == 'GET':
        p_admin = request.args.get('username', None)
        p_email = request.args.get('email', None)
        p_password = request.args.get('password', None)
    else:
        p_admin = request.form.get('username',None)
        p_email = request.form.get('email',None)
        p_password = request.form.get('password',None)

    if not p_admin or not p_password:
        return ReturnUtil.Error(msg="输入参数非法")

    newobj = Admin(username=p_admin, email=p_email, password=PasswdUtil.md5(p_password))
    db.session.add(newobj)
    db.session.commit()
    # admins = Admin.query.all()
    return ReturnUtil.Success(data=newobj)
